import pandas as pd

# 原始数据
test_data = [
    ['1761638400000', '114179.4', '114471.9', '114097.6', '114406.5', '212.00456223', '24239327.413813702', '24239327.413813702', '0'],
    ['1761634800000', '114116.1', '114366.8', '114090', '114179.5', '387.89129446', '44302232.250207421', '44302232.250207421', '1'],
    ['1761631200000', '113614.4', '114189.9', '113608', '114116', '171.52991594', '19548472.217300338', '19548472.217300338', '1'],
    ['1761627600000', '113963', '113999.6', '113440.3', '113612', '193.79009923', '22040376.704524662', '22040376.704524662', '1']
]


def cal_macd(raw_data):
    # 整理为DataFrame
    df = pd.DataFrame(raw_data, columns=['timestamp', 'open', 'high', 'low', 'close', 'vol', 'volCcy', 'volCcyQuote', 'confirm'])
    df["close"] = df["close"].astype(float)
    df['Date'] = pd.to_datetime(df['timestamp'].astype(int), unit='ms')
    df.set_index('Date', inplace=True)
    df = df.sort_index()
    # MACD计算
    df['ema12'] = df['close'].ewm(span=12, adjust=False).mean()
    df['ema26'] = df['close'].ewm(span=26, adjust=False).mean()
    df['dif'] = df['ema12'] - df['ema26']
    df['dea'] = df['dif'].ewm(span=9, adjust=False).mean()
    df['macd'] = 2 * (df['dif'] - df['dea'])  # MACD柱子
    return df

def is_macd_bar_increasing(df, consecutive=2):
    """
    判断MACD Bar最近是否有consecutive根连续放大
    放大指绝对值连续增加
    """
    macd_bars = df['macd'].values[-consecutive:]
    if len(macd_bars) < consecutive:
        return False
    # 取出需要比较的若干根（如最后两根比较一次，最后三根比较两次）
    for i in range(1, len(macd_bars)):
        if abs(macd_bars[i]) <= abs(macd_bars[i-1]):
            return False
    return True

if __name__ == '__main__':
    import okx.MarketData as MarketData
    flag = "0"
    marketDataAPI =  MarketData.MarketAPI(flag=flag)
    result = marketDataAPI.get_candlesticks(instId="BTC-USDT",bar = '1H')
    raw_data = result["data"]
    df = cal_macd(raw_data)
    print (is_macd_bar_increasing(df,3))
